{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f6895d702ee940bbaf596cb26b1a62ba",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Viewer(cmap='jet', geometries=[], gradient_opacity=0.01, point_sets=[], rendered_image=<itkImagePython.itkImag…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\"\"\"Menger fractal sponge.\"\"\"\n",
    "\n",
    "# Credits: K3D authors at:\n",
    "# https://github.com/K3D-tools/K3D-jupyter/tree/master/examples\n",
    "# https://en.wikipedia.org/wiki/Menger_sponge\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "iteration = 4\n",
    "\n",
    "size = 3**iteration\n",
    "voxels = np.ones((size, size, size));\n",
    "\n",
    "def iterate(length, x, y, z):\n",
    "\n",
    "    nl = length // 3\n",
    "    if nl < 1: return\n",
    "\n",
    "    margin = (nl-1) // 2\n",
    "    voxels[z-margin:z+margin+1, y-margin:y+margin+1, :] = 0\n",
    "    voxels[z-margin:z+margin+1, :, x-margin:x+margin+1] = 0\n",
    "    voxels[:, y-margin:y+margin+1, x-margin:x+margin+1] = 0\n",
    "\n",
    "    for ix,iy,iz in np.ndindex((3,3,3)):\n",
    "        if (1 if ix !=1 else 0) + (1 if iy != 1 else 0) + (1 if iz != 1 else 0) !=2:\n",
    "            iterate(nl, x + (ix-1) * nl, y + (iy-1) * nl , z + (iz-1) * nl)\n",
    "\n",
    "iterate(size, size//2, size//2, size//2)\n",
    "\n",
    "\n",
    "from vtkplotter import *\n",
    "\n",
    "embedWindow('itkwidgets') # or k3d\n",
    "\n",
    "#create a Volume from the numpy object and show it:\n",
    "Volume(voxels).show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
